package com.xiaotao;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;


/**
 * @author xiaotao
 */
@Slf4j
public class TcpClient {
    private static final String TAG = "TcpClient";
    // ESP8266 IP 地址
    private final String serverIp;
    // ESP8266 端口
    private final int serverPort;
    // Socket 连接
    private Socket socket;
    // 输入流
    private InputStream inputStream;
    // 输出流
    private OutputStream outputStream;
    // 连接状态
    private boolean isConnected = false;

    // 构造方法，传入目标 ESP8266 的 IP 地址和端口号
    public TcpClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    // 连接到 ESP8266
    public void connect() {
        // 异步任务：连接到服务器
        ThreadUtil.execute(()->{
            try {
                // 创建 Socket 连接
                socket = new Socket();
                // 设置连接超时 5 秒
                socket.connect(new InetSocketAddress(serverIp, serverPort), 5000);

                // 获取输入输出流
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();

                isConnected = true;
                System.out.println("Connected to server: " + serverIp + ":" + serverPort);
                sendData("ookokokokkokok".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    // 发送数据到 ESP8266
    public void sendData(byte[] data) {
        if (isConnected && socket != null && outputStream != null) {
            try {
                outputStream.write(data);
                outputStream.flush();
                System.out.println("Data sent: " + new String(data));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 接收来自 ESP8266 的数据
    public byte[] receiveData() {
        byte[] buffer = new byte[1024];
        int bytesRead = 0;

        if (isConnected && inputStream != null) {
            try {
                bytesRead = inputStream.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (bytesRead > 0) {
            byte[] result = new byte[bytesRead];
            System.arraycopy(buffer, 0, result, 0, bytesRead);
            return result;
        }
        return null;
    }

    // 关闭连接
    public void disconnect() {
        if (isConnected) {
            try {
                inputStream.close();
                outputStream.close();
                socket.close();
                isConnected = false;
                System.out.println("Disconnected from server");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 用于调试
    public boolean isConnected() {
        return isConnected;
    }
}
